package com.honeybee.cloud.framework.validation.utils;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @Description hibernate-validator  Validation工具类
 * @Author DELL
 * @Create 2019-04-25
 * @Since 1.0.0
 */
public class ValidatorUtils {
    /**
     * 使用hibernate的注解来进行验证
     */
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 功能描述: <br>
     * 〈注解验证参数〉
     *
     * @param obj
     * @param groups 检验组
     * @see
     * @since
     */
    public static <T> void validate(T obj, Class<?>... groups) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj,groups);
        // 抛出检验异常
        if (constraintViolations.size() > 0) {
            throw new ConstraintViolationException(constraintViolations.iterator().next().getMessage(),constraintViolations);
        }
    }
}
